<?php
/**
 * @Author: king
 * @Date:   2019-05-16 20:27:07
 * @Last Modified by:   king
 * @Last Modified time: 2019-06-02 00:00:10
 */

namespace App\Models\Api;
use App\Exceptions\ApiException;
use App\Models\Api\Base;
use App\Models\Api\Orders;

class LanmeiOrderRefund extends Base
{
    protected $table = 'astro_order_refund';

    /*
     * 获取订单的退款信息
     */
    public function getOrderRefund($id = 0)
    {
        try
        {
            $data = $this
                ->from('astro_order_refund as r')
                ->select('r.price','r.return_time','rt.name')
                ->join('astro_order_refund_type as rt', 'r.type','=','rt.id')
                ->where('oid', $id)
                ->get();
               
            $data = json_decode(json_encode($data, true), true);
        }
        catch (\Exception $e)
        {
           throw new ApiException('获取退款信息失败,请重新登录', 200,config('code.error'));
        }
        return $data;
    }

    /**
     * 生成退款订单
     * @param $order_id string 订单ID
     * @param $type int 退款类型
     * @param $price float 退款金额
     * @return string
     * @throws ApiException
     */
    public function creatOrder(string $order_id, int $type, $price = null)
    {
        try
        {
            // 获取订单信息
            $orderInfo = (new Orders())->from('orders as o')->join('astro_order_refund as or', 'or.oid','=','o.id', 'left')
                ->where('o.order_id', $order_id)->select('o.id','o.total_amount','o.trade_type','o.total_amount','o.order_type','or.refund_id')->orderBy('or.id','desc')->first();

            // 生成退款单号
            if ($orderInfo['refund_id'])
            {
                $refund_id = $order_id . sprintf('%03d', (substr($orderInfo['refund_id'], -3) + 1));
            } else
            {
                $refund_id = $order_id . '001';
            }
            $price = $price ?? $orderInfo['total_amount'];

            $refundData = [
                'oid' => $orderInfo['id'],
                'order_id' => $order_id,
                'refund_id' => $refund_id,
                'type' => $type,
                'price' => $price,
                'create_time' => time(),
                'status' => 1,
                'trade_type' => $orderInfo['trade_type']
            ];
            // 创建退款单号
            $this->save($refundData);
        }
        catch (Exception $e)
        {
            throw new ApiException($e->getMessage(), 200, config('code.error'));
        }

        return $refund_id;
    }
}
